package com.example.webcrawlercoursedesign;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jawor
 * Time: 2018/5/28
 */

public class FragmentHupu extends Fragment {
	private Context context;
    private List<News> newsList;//添加新闻
    private NewsAdapter adapter;//新闻适配器
    private Handler handler;
    private ListView listView;//展示新闻列表
	private NewsCache cache;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        context = getActivity();
    	//fragment的布局
        View fragmentView = inflater.inflate(R.layout.fragment_hupu, container, false);
        newsList = new ArrayList<>();//新闻列表
        listView = fragmentView.findViewById(android.R.id.list);
        cache = new NewsCache(context);
        getNews(context);//获取新闻
        /**
         * 又开一个线程
         *判断message
         * 装上适配器
         * 适配器版本的点击事件
         */
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    adapter = new NewsAdapter(context, newsList);//适配器
                    listView.setAdapter(adapter);//设置适配器
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//这一部分是点击之后转到新闻内容页面
                            /**
                             * 获取位置,把数据装进news
                             * intent切换布局
                             * 传输数据
                             * 启动
                             */
                            News news = newsList.get(position);//往定好数据框架的news里面传入数据
                            Intent intent = new Intent(getActivity(), NewsDisplayActivity.class);//转到展示新闻的界面
                            intent.putExtra("news_url", news.getNewsUrl());//把要打开的网址给他
                            startActivity(intent);
                        }
                    });
                }
            }
        };
        return fragmentView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    private void getNews(final Context context) {


        new Thread(new Runnable() {
            @Override
            public void run() {
	            if (!cache.isNetworkAvailable(context)){//无网络连接时加载库数据
		            newsList = cache.loadCache(MySQLite.HUPU_NAME);
	            }
	            else {
		            try{
			            for(int i = 1;i<=5;i++) {
				            Document doc = Jsoup.connect("https://m.hupu.com/nba/news/"
						            + Integer.toString(i)).userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36").get();
				            //手机虎扑nba新闻版块前5页
				            Elements links = doc.select("li");    //解析来获取每条新闻的信息
				            //for循环遍历获取到每条新闻的五个数据并封装到News实体类中
				            for(int j = 0;j < links.size();j++){
					            Element element = links.get(j);//第j条新闻
					            String title = element.select("h3").text();
					            String url = "https:" + element.select("a").attr("href");
					            String time = element.select("span.news-source").text() + " " +
							            element.select("span.news-time").text();
					            String image = element.select("div.img-wrap").attr("style");
					            String imageUrl = image.substring(image.lastIndexOf('(') + 1,
							            image.lastIndexOf(')'));
					            News news = new News(title, url,null, time, imageUrl);
					            newsList.add(news);
				            }
			            }
			            cache.updateCache(newsList, MySQLite.HUPU_NAME);//更新数据库
		            }catch (Exception e){
			            e.printStackTrace();
		            }
	            }
	            Message msg = new Message();
	            msg.what = 1;
	            handler.sendMessage(msg);
            }
        }).start();
    }


}
